﻿var workingItems = new Array();
var sourcePreviewer;
var sharepointPreviewer;
var mergePreviewer;

$(document).ready(function () {
    loadSharepointItem("All");
    //loadSourceCSS();

    //$("option:first", "#listSourceCSS").trigger("click");
    $("#listSourceCSS").click(function () {
        // updateSelectorPreview($(this).val())
    });
    $("#listSharepointCSS").change(function () {
        getItem($(this).val());
    });
    $("#listSourceCSS").change(function () {
        //alert("change");
        updateSelectorPreview($(this).val())
    });
    $.each($("option", $("#listSourceCSS")), function () {

        workingItems.push($(this).val());
    });

    //    $("option", $("#listSourceCSS")).click(function () {

    //        updateSelectorPreview($(this).val())
    //    });

    $("#filterSource").bind("change", function (e) {
        filter($(this), $("#listSourceCSS"));
    });
    $("#filterSharepoint").bind("change", function (e) {
        //filter($(this), $("#listSharepointCSS"));
        loadSharepointItem($(this).val());
    });

    $("#add").click(function () {

        var source = $("#listSourceCSS");
        var sharepoint = $("#listSharepointCSS");
        var mapping = $("#listMappingCSS");

        var sourceItem = source.find(":selected");
        var sharepointItem = sharepoint.find(":selected");

        if (sourceItem != null && sharepointItem != null) {
            var text = sourceItem.val() + "  -  " + sharepointItem.text();
            var value = sourceItem.val() + "," + sharepointItem.val() +"," + $("#hiddenCurrentIndexSession").val();

            var match = $("#listMappingCSS option[value='" + value + "']")[0];
            if (match == null) {

                mapping.append($("<option></option>").attr("value", value).attr("selected", "true").text(text));
            }
            else alert('Duplicated mapping');
        }
        updatePreview();
        return false;
    });

    $("#remove").click(function () {

        var source = $("#listSourceCSS");
        var sharepoint = $("#listSharepointCSS");
        var mapping = $("#listMappingCSS");

        //var sourceItem = source.find(":selected").val();

        var mappingItem = mapping.find(":selected");
        if (mappingItem.prev() != null) mappingItem.prev().attr("selected", "selected");
        else
            if (mappingItem.next() != null) mappingItem.next().attr("selected", "selected");

        if (mappingItem != null) mappingItem.remove();

        updatePreview();
        return false;
    });
    $("input[type='radio']").change(function () { updatePreview(); });
    //    // initialize with parameters
    //    var flashvars = {
    //        parser: "css",
    //        showcolumns: false,
    //        readOnly: false,
    //        preferredFonts: "|Fixedsys|Fixedsys Excelsior 3.01|Fixedsys Excelsior 3.00|Courier New|Courier|",
    //        onload: function () {
    //            // call setText to load content into editor
    //            //document.getElementById('ctlFlash').setText(document.getElementById('csspreview').value);
    //            //document.getElementById('csspreview').style.display = 'none';
    //            //updatePreview();
    //        }
    //    };

    //    // flash player parameters, you can find more information at: http://code.google.com/p/swfobject/wiki/documentation
    //    var params = { menu: "false", wmode: "transparent", allowscriptaccess: "always" };

    //    // define the id of the flash control, we need the id in javascript interaction 
    //    var attributes = { id: "ctlFlash", name: "ctlFlash" };

    //    var attributes1 = { id: "ctlFlashPreviewSource", name: "ctlFlashPreviewSource", showcolumns: false };
    //    var attributes2 = { id: "ctlFlashPreviewSP", name: "ctlFlashPreviewSP", showcolumns: false };
    //    // embed the flash with size, more information can be found at: http://code.google.com/p/swfobject/wiki/documentation
    //    swfobject.embedSWF("Scripts/CodeHighlightEditor.swf", "flashContent", "600", "485", "10.0.0", null, flashvars, params, attributes);
    //    swfobject.embedSWF("Scripts/CodeHighlightEditor.swf", "preview1", "250", "120", "10.0.0", null, flashvars, params, attributes1);
    //    swfobject.embedSWF("Scripts/CodeHighlightEditor.swf", "preview2", "250", "120", "10.0.0", null, flashvars, params, attributes2);

    var emptyPattern = /^\s*$/;
    if (!emptyPattern.test($("#error").html())) {

        $("#error").show().fadeIn(3000);

        setTimeout(function () {
            $("#error").fadeOut().hide();

        }, 10000);
    }
    //DO INIT ACTION 
    setTimeout(function () {
        $("#listSourceCSS option:first").attr("selected", "true");
        $("#listSourceCSS").trigger("change");
    }, 1000);
    sharepointPreviewer = CodeMirror.fromTextArea(document.getElementById("sharepointPreviewer"), {});
    sourcePreviewer = CodeMirror.fromTextArea(document.getElementById("sourcePreviewer"), {});
    mergePreviewer = CodeMirror.fromTextArea(document.getElementById("mergePreviewer"), {});
});

function loadContent(lang, css, ctrl) {
    try {
        document.getElementById(ctrl).setParser(lang);
        document.getElementById(ctrl).setText(css);
    } catch (e) { }
}

function updatePreview() {
    //TODO : This function is out of scope, just it to make continue implement in future.
    
    var string = "";
    var previewAll = $("input[type='radio']:checked").val();

    $.each($("#listMappingCSS").children("option"), function () {
        string += $(this).val() + "|";
    });
    $("#_mappings").val(string);
    return;
    // alert('call ajax :' + string);
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/GetUpdate",
        data: "{mappings: '" + string + "', mode : '" + previewAll +"'}",
        dataType: "json",
        success: function (msg) {
            loadContent("css", msg.d,"ctlFlash");
        },
        error: function () {
            alert("An error occurred on the server.");
        }
    });

}

function filter(dropdown, select) {
    
    var value = dropdown.val();
    $("option", select).remove();
    //alert("test");
    $.each(workingItems, function (s) {
        var v = "" + this; ;

        if ((value == '*') ||
                    (value == "." && v.substr(0, 1) == value.substr(0, 1))
                     || (value == "#" && v.substr(0, 1) == value.substr(0, 1))
                     || (value == '+' && v.substr(0, 1) != '.' && v.substr(0, 1) != '#')
                    ) {

            select.append($("<option></option>").attr("value", v).attr("selected", "true").text(v));
            select.add("option");
        }
    });
    $("option:first", select).attr("selected", true);
    select.trigger("click");
    
//    $.each(select.children("option"), function () {

//        var v = $(this).val();
//        //alert(v.substr(0, 1));
//        if ((value == '*') ||
//                    (value == "." && v.substr(0, 1) == value.substr(0, 1))
//                     || (value == "#" && v.substr(0, 1) == value.substr(0, 1))
//                     || (value == '+' && v.substr(0, 1) != '.' && v.substr(0, 1) != '#')
//                    ) {

//            $(this).show();
//        }
//        else {
//            //alert("hide --- " + v);
//            //$(this).attr("disabled", "disabled");
//            $(this).hide();
//        }
//        
//    });
}

function updateSelectorPreview(selector) {
    if (selector == null) return;
    var dpItemId = $("#listSharepointCSS").val();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/GetSelectorContent",
        data: "{selector: '" + selector + "', sharepointId: " + dpItemId + "}",
        dataType: "json",
        success: function (msg) {
            sourcePreviewer.setValue(msg.d.Source);
            mergePreviewer.setValue(msg.d.MergedSource);
            preparePreview(msg.d.Source);

        },
        error: function () {
            alert("An error occurred on the server.");
        }
    });
}
function loadSharepointItem(area) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/GetSPItems",
        data: "{area: '" + area + "'}",
        dataType: "json",
        success: function (msg) {
            var items = msg.d;
            $("#listSharepointCSS option").remove(); //.each(function() {$(this).remove()});
            if (items != null && items.length > 0) {
                var listSharepointCSS = $("#listSharepointCSS");

                for (var i = 0; i < items.length; i++) {
                    listSharepointCSS.append($("<option></option>").attr("value", items[i].Id).text(items[i].Name));
                }
                $("option:first", listSharepointCSS).attr("selected", true);

                    setTimeout(function () { getItem(items[0].Id) }, 1000);
            }
            listSharepointCSS.click(function () {

               // getItem($(this).val());
            });
        },
        error: function () {
            alert("An error occurred on the server.");
        }
    });

}
function getItem(id) {
    var source = $("#listSourceCSS").val();
    if (source == null) source="";
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/GetItem",
        data: "{id: '" + id + "', source:'" + source + "'}",
        dataType: "json",
        success: function (msg) {
            //loadContent("css", msg.d.Style, "ctlFlashPreviewSP");
            var item = msg.d.Item;
            var mergeSource = msg.d.MergeSource;
            mergePreviewer.setValue(mergeSource);
            sharepointPreviewer.setValue(item.Style);

            $("#previewImage").attr("src", "PreviewImage.ashx?f=" + item.Image);
            $("#previewImage").show();
        },
        error: function () {
            alert("An error occurred on the server.");
        }
    });
}
function loadSourceCSS() {
    var array = new Array();

    $.each($("option", $("#listSourceCSS")), function () {
        //alert($(this).val());
        array.push($(this).val());
        $(this).remove();
    });
    $.each(array, function () {
        
        $("#listSourceCSS").append("<option></option>").attr("value", this).attr("selected", "true").text(this);
//                           .click(function () {
//        
//                                 alert('hello');
//                            }));

    });

    $("#listSourceCSS").click(function() {alert('check')});

   // alert(array);
}
function preparePreview(css) {
    var previewHolder = $("#sourcePreview");
//     var emptyPattern = /^\s*$/;
//     if (emptyPattern.test($("#error").html())) {
//         previewHolder.css("visibility", "hidden");
//         return;
//     }
//    
//    previewHolder.css("visibility","visible");
    previewHolder.css("color", "blue");
    previewHolder.attr("style", css);
    previewHolder.show();

    var removeStyles = ["position", "z-index", "width", "height", "max-height", "max-width", "min-height", "min-width","visibility","display","position","top","left","right","bottom","float","background-image","background-repeat","background-position","background-attachment"];
    $.each(removeStyles, function () {
        var style="" +this;
        previewHolder.css(style, "");

    });
    var cssPreviewContainer = $("#cssPreviewContainer");
    if (previewHolder.css("color") == "rgb(255, 255, 255)" || previewHolder.css("background-color") == "rgb(255, 255, 255)") {
        cssPreviewContainer.css("background-color", "black");
    }
    else {
        cssPreviewContainer.css("background-color", "white");
    }
    
    //previewHolder.css("position", "");
    //previewHolder.css("z-index", "");
    //previewHolder.css("width", "");
    
}